/**
 * 
 */
package cz.geoserver.KMLpublisher.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet for processing simple HTML client to insert SQL SELECT query
 * @author mkepka
 *
 */
public class FormServlet extends HttpServlet{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    private String dataTabPar = "data_table";
    private String dataTabVal = "";
    private String clustAttPar = "clustered_att";
    private String clustAttVal = "";
    private String queryPar = "query";
    private String queryVal ="";
    private String queryValDefault = "SELECT asKML(the_geom), * FROM any_table;";

    /**
     * Method processes simple form to insert SQL SELECT query
     * and data table and clustered attribute name if hierarchy is used.
     * After checking are values redirect to Servlet that generates KMLs
     *
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter pw = resp.getWriter();
        Map paramMap = req.getParameterMap();
        if(paramMap.containsKey(queryPar)){
            queryVal = req.getParameter(queryPar);
            if(queryVal.equalsIgnoreCase(queryValDefault) || queryVal.isEmpty()){
                pw.write("You must insert any another SQL SELECT command!");
            }
            else{
                if(paramMap.containsKey(dataTabPar) || paramMap.containsKey(clustAttPar)){
                    dataTabVal = req.getParameter(dataTabPar);
                    clustAttVal = req.getParameter(clustAttPar);
                    if(!dataTabVal.isEmpty() && !clustAttVal.isEmpty()){
                        resp.sendRedirect("DKMLServlet?data_table="+dataTabVal+"&clustered_att="+clustAttVal+"&query="+queryVal);
                    }
                    else{
                        resp.sendRedirect("DKMLServlet?&query="+queryVal);
                    }
                }
                else{
                    resp.sendRedirect("DKMLServlet?&query="+queryVal);
                }
            }
        }
        else{
            pw.write("Request does not contain field with SQL!");
        }
    }
}